// pages/feastPage/notOwner/notOwner.js
var netWork = require('../../../utils/netWork.js');
var api = require('../../../utils/api.js');

const log = require('../../../utils/logs.js');
var isClick = true;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imagesUrl: getApp().globalData.imagesUrl,
    topHeight: 0,
    height: 1048,
    triggered: false,
    pageNum: 1,
    feastOpenList: [],
    ani: 0, //动画是否执行
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    try {
      const {
        SDKVersion = ''
      } = wx.getSystemInfoSync();
      // 获取系统信息
      const that = this;
      wx.getSystemInfo({
        success: function (res) {
          that.setData({
            addHeight: (res.screenHeight * res.pixelRatio - 1334) / 6
          });
        }
      });
      console.log(that.data.addHeight)
      log.info(SDKVersion)
      const compatibility = util.compareVersion(SDKVersion, '2.2.2');
      log.info(compatibility)
      if (compatibility == -1) {
        wx.showModal({
          content: '您的微信版本过低，请升级后再来吧~',
          confirmText: '我知道了',
          showCancel: false
        });
        return;
      }
    } catch (e) {}
    try {
      // 检测是否可以调用getUpdateManager检查更新
      if (!wx.canIUse("getUpdateManager")) return;
      let updateManager = wx.getUpdateManager();
      // 获取全局唯一的版本更新管理器，用于管理小程序更新
      updateManager.onCheckForUpdate(function (res) {
        log.info(res)
        // 监听向微信后台请求检查更新结果事件
        log.info("是否有新版本：" + res.hasUpdate);
        if (res.hasUpdate) {
          //如果有新版本
          // 小程序有新版本，会主动触发下载操作
          updateManager.onUpdateReady(function () {
            //当新版本下载完成，会进行回调
            wx.showModal({
              title: '更新提示',
              content: '新版本已经准备好，单击确定重启小程序',
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                  // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启小程序
                  updateManager.applyUpdate();
                }
              }
            })
          })
          // 小程序有新版本，会主动触发下载操作（无需开发者触发）
          updateManager.onUpdateFailed(function () {
            //当新版本下载失败，会进行回调
            wx.showModal({
              title: '提示',
              content: '检查到有新版本，但下载失败，请稍后尝试',
              showCancel: false,
            })
          })
        }
      });
    } catch (e) {
      e
    }
    //高度处理
    let topHeight = wx.getStorageSync('statusBarHeight') + wx.getStorageSync('navigationBarHeight');
    this.setData({
      topHeight: topHeight,
      icon:  'common/loading',
      activityBanquetId: options.activityBanquetId
    });
    api.judgeNetworkStatus(function (res) {
      if ("none" == res) return;
    })
    this.changeHeight();
    this.queryFeastOpenList();
  },

  lower() {
    this.queryFeastOpenList();
  },
  back() {
    wx.navigateBack({
      delta: 1
    });
  },
  reGetPrize(event) {

    api.judgeNetworkStatus(function (res) {
      if ("none" == res) return;
    })
    let prizeInfo = event.currentTarget.dataset.prizeinfo;
    let index = event.currentTarget.dataset.index;
  
    if (prizeInfo.status == '8') {
      return;
    }
    //防止重复点击或者点击过快
    console.log("点击了");
    if (!isClick) {
      console.log("重复返回~");
      return;
    }
    if (isClick) {
      isClick = false;
      //定时器
      setTimeout(function () {
        isClick = true;
      }, 3000); //3秒内不能重复点击
    }
    this.isLoading(true, "正在领取...")
    const that = this;
   

    //兑奖
    netWork.POST('receiveWxRedBag', {
      data: {
        userId: wx.getStorageSync('userId'),
        prizeOrderId: prizeInfo.prizeOrderId,
        prizeId: prizeInfo.prizeId,
        positioningStyle:'0' ,
        positioningType: '-1',
        latitude: wx.getStorageSync('latitude'),
        longitude: wx.getStorageSync('longitude'),
        speed: wx.getStorageSync('speed'),
        accuracy: wx.getStorageSync('accuracy'),
        source: 1, //兑奖来源，1-正常流程兑奖 2-中奖记录兑奖
      },
      success: function (res) {
        that.isLoading(false)
        if (res.data.retCode == undefined) {
             //错误提示
             that.setData({
              showAlert: true, 
              alertContent: '领取失败,请稍后重试'
            })
        }
        if (res.data.retCode == "0000") {
          wx.showToast({
            title: '领取成功',
            icon: 'success'
          })
          //更新该prizeOrderid对应的状态
          that.setData({
            ['feastOpenList[' + index + '].status']: 8
          })

        } else {
         //错误提示
         that.setData({
          showAlert: true, 
          alertContent: '领取失败,请稍后重试['+res.data.retCode+']'
        })
        }

      },
      fail: function () {
        that.isLoading(false)
          //错误提示
          that.setData({
            showAlert: true, 
            alertContent: '领取失败,请稍后重试'
          })
      }
    });


  },

  isLoading(isLoading, loadingText) {
    this.setData({
      isLoading: isLoading,
      loadingText: loadingText
    })
  },
  ok() {
    this.setData({
      barcode: '',
      alertContent: '',
      showAlert: false
    })
  },

  queryFeastOpenList() {
    const that = this;
    if (that._freshing) return
    that._freshing = true;
    that.isLoading(true, '加载中...')
    netWork.POST_Json('banquet/openedInfo', {
      data: {
        activityBanquetId: that.data.activityBanquetId,
        pageNum: that.data.pageNum,

      },
      success: function (res) {
        that.isLoading(false)
        setTimeout(function () {
          that.setData({
            triggered: false,

          })
          that._freshing = false;
        }, 1000);
        if (res.data.retCode == undefined) {
          wx.showToast({
            title: '查询失败，稍后重试',
            icon: 'none'
          })
        }
        if (res.data.retCode == '0000') {
          let list = that.data.feastOpenList;
          if(res.data.data.length>0){
            that.setData({
              feastOpenList: list.concat(res.data.data),
              pageNum: that.data.pageNum + 1
            });
          }
          

        } else {
          wx.showToast({
            title: '查询失败，稍后重试',
            icon: 'none'
          })
        }
      },
      fail: function (res) {
        that.isLoading(false)
        setTimeout(function () {
          that.setData({
            triggered: false,

          })
          that._freshing = false;
        }, 1000);
        wx.showToast({
          title: '查询失败，稍后重试',
          icon: 'none'
        })
      }
    });
  },
  //下拉刷新中奖记录
  async onRefresh() {
    api.judgeNetworkStatus(function (res) {
      if ("none" == res) return;
    })
    this.setData({
      pageNum: 1,
      feastOpenList: []
    });
    this.queryFeastOpenList();


  },
  changeHeight() {
    const that = this;
    // if (that.data.height != 527) {
    //   return;
    // }
    let query = wx.createSelectorQuery();
    query.select('.image1').boundingClientRect(rect => {
      let clientWidth = rect.width;
      let ratio = 750 / clientWidth;
      let clientBottom = rect.bottom;
      console.log(ratio);
      let clientHeight = wx.getSystemInfoSync().windowHeight * ratio;

      console.log('屏幕高度' + clientHeight);
      console.log('按钮高度' + clientBottom * ratio);
      let bottom = clientHeight - (clientBottom * ratio) - 48;
      if (bottom >= 0) {
        that.setData({
          height: 1018 + bottom,
        })
      }

      console.log("距离底部的高度：" + bottom)
    }).exec();

  },
  handlerGobackClick() {
    wx.navigateBack({
      delta: 1
    });}
})